from django import forms as forms
import logging
from django.utils import simplejson
from django.forms.extras.widgets import SelectDateWidget
from django.forms.widgets import RadioSelect, CheckboxInput, Select, NullBooleanSelect, SelectMultiple


class NakedLabelWidget(forms.Widget):
  """
  A widget that produces a naked label
  """
  def __init__(self, attrs=None):
    ""
    logging.debug("init NLW")
    super(NakedLabelWidget, self).__init__(attrs)

  def render(self, name, value, attrs=None):
     return '' #super(NakedLabelWidget, self).render( attrs)

class NakedLabelField(forms.NullBooleanField):
      logging.debug("init NLF")
      widget = NakedLabelWidget(attrs={'class':'special'})

class CheckboxWidget(forms.CheckboxInput):
  """
  A Checkbox widget that saves data compatible with json forms 
  """
  def __init__(self, attrs=None):
    ""
    logging.debug("init CBW")
    super(CheckboxWidget, self).__init__(attrs, check_test=bool)


#takes a string of Extjs xtypes and creates a Django form 
class DjFormFromXtype(forms.Form):
    def __init__ (self, listOfdict, *args, **kwargs):
        forms.Form.__init__ (self, *args, **kwargs)
        hdrdict = None
        for df in listOfdict:
          i = None
          fld = None
          dfkeys = df.keys()
          n = dfkeys[0]
          i = df[n]
          if i['xtype'] == 'header':
            hdrdict = i
          if i.has_key('initial'):
            if i['xtype'] == 'CharField':
              fld = forms.CharField(required= i['required'], label=i['fieldLabel'], initial=i['initial'],widget=forms.TextInput(attrs={'class':'special'}))
              self.fields[n] = fld
            if i['xtype'] == 'EmailField':
              fld = forms.EmailField(required= i['required'], label=i['fieldLabel'], initial=i['initial'], widget=forms.TextInput(attrs={'class':'special'}))
              self.fields[n] = fld
            if i['xtype'] == 'DateField':
              edate = str(i['initial'])
              if '/' in edate:
                m, d, y = edate.split('/')
                edate =  "%s-%s-%s" % (y,m,d)
              fld = forms.DateField(required= False, label=i['fieldLabel'], initial=edate, widget=SelectDateWidget(attrs={'class':'special'}))
              self.fields[n] = fld
            if i['xtype'] == 'ComboField':
              fld = forms.ChoiceField(required= False, label=i['fieldLabel'], initial=i['initial'], choices=i['store'], widget=Select())
              self.fields[n] = fld
            if i['xtype'] == 'Checkbox':
              if str(i['initial']) in ['False', 'off']:
                i['initial'] = ''
              if str(i['initial']) == 'on':
                i['initial'] = True
              fld = forms.BooleanField(required=False, label= i['fieldLabel'], initial= i['initial'], widget=CheckboxWidget(attrs={'class':'special', 'value':'on'}))
              self.fields[n] = fld
            if i['xtype'] == 'Label':
              fld = NakedLabelField(label=i['fieldLabel']) 
              self.fields[n] = fld
            if i['xtype'] == 'TextArea':
              fld = forms.CharField(required= i['required'], label=i['fieldLabel'], initial=i['initial'] , widget=forms.Textarea(attrs={'rows':'20', 'cols':'32', 'class':'special'}))
              self.fields[n] = fld
            if i['xtype'] == 'RadioField':
              TheChoices=hdrdict[i['name']]
              lb = ''
              if i.has_key('fieldLabel'): lb = i['fieldLabel']
              else: lb = i['name']
              fld = forms.ChoiceField(initial=i['initial'], widget=forms.RadioSelect(), choices=TheChoices, label='')
              self.fields[n] = fld
          else:
            if i['xtype'] == 'CharField':
              fld = forms.CharField(required=i['required'], label=i['fieldLabel'], widget=forms.TextInput(attrs={'class':'special'}))
              self.fields[n] = fld
            if i['xtype'] == 'EmailField':
              fld = forms.EmailField(required= i['required'], label=i['fieldLabel'], widget=forms.TextInput(attrs={'class':'special'}))
              self.fields[n] = fld
            if i['xtype'] == 'DateField':
              fld = forms.DateField(required= False, label=i['fieldLabel'],  widget=SelectDateWidget(attrs={'class':'special'}))
              self.fields[n] = fld
            if i['xtype'] == 'Checkbox':
              fld = forms.BooleanField(required=False, label= i['fieldLabel'],  widget=CheckboxWidget(attrs={'class':'special', 'value':'on'}))
              self.fields[n] = fld
            if i['xtype'] == 'Label':
              fld = NakedLabelField(label=i['fieldLabel']) 
              self.fields[n] = fld
            if i['xtype'] == 'TextArea':
              fld = forms.CharField(required= i['required'], label=i['fieldLabel'], widget=forms.Textarea(attrs={'rows':'20', 'cols':'32', 'class':'special'}))
              self.fields[n] = fld
            if i['xtype'] == 'RadioField':
              lb = ''
              if i.has_key('fieldLabel'): lb = i['fieldLabel']
              else: lb = i['name']
              TheChoices=hdrdict[i['name']]
              fld = forms.ChoiceField(label='', widget=forms.RadioSelect(), choices=TheChoices,)
              self.fields[n] = fld
            if i['xtype'] == 'ComboField':
              fld = forms.ChoiceField(required= False, label=i['fieldLabel'], choices=i['store'], widget=Select( attrs={'class':'special'}))
              self.fields[n] = fld






def xtypeToDjango(xtypeform, jsondata=None, htmlout=None):
	#converts jsonform into html with data via creation of django form
        # initial values are set to jsondata. Cannot just pass into django form because then validation is triggered TODO: research
	#convert extjsform to true json
	p1 = xtypeform.replace('Ext.ux.plugins.RemoteValidator', '"Ext.ux.plugins.RemoteValidator"')
	p2 = p1.replace(':false', ':"False"').replace(':true', ':"True"').replace('trythis','"trythis"')
	xtypeform = p2
        formobj = None
        if jsondata:
          try:
                  dataobj = simplejson.loads(jsondata) #turn jsondata into a dict
          except:
                  logging.info("unable to load jsondata via simplejson")
        else:
          dataobj = {}
	#split on ',' then join to ignore spaces eg. "},  {"
	commasplit = xtypeform.split(',')
	commasplit = [ x.strip() for x in commasplit ]
	xtypeform = ','.join(commasplit)
	listofxtypes = "[" + xtypeform + ']'
        flatlistofxtypes = []
        try:
          formobj = simplejson.loads(listofxtypes)
          logging.debug(formobj)
        except:
          logging.info("Unable to process xtypeform: " + str(listofxtypes))
        #descend into tab panel loops and flatten
        if str(type(formobj)) == "<type 'list'>":
          for f in formobj:
            logging.debug(f)
            if f.has_key('items'):
              items1obj = f['items']
              f['items'] = ''
              if str(type(f)) == "<type 'dict'>" : flatlistofxtypes.append(f)
              for i in items1obj:
                if i.has_key('items'):
                  items2obj = i['items']
                  i['items'] = ''
                  if str(type(i)) == "<type 'dict'>" : flatlistofxtypes.append(i)
                  if str(type(items2obj)) == "<type 'dict'>" : flatlistofxtypes.append(items2obj)
                  for j in items2obj:
                    if str(type(j)) == "<type 'dict'>" : flatlistofxtypes.append(j)
                else:
                  if str(type(i)) == "<type 'dict'>" : flatlistofxtypes.append(i)
            else:
              if str(type(f)) == "<type 'dict'>" : flatlistofxtypes.append(f)
	res = ''
        #create django form header for radio choices
        ff = [{u'header': {'xtype': u'header'}},] # a list of dict
        for fx in flatlistofxtypes:
          df = {}
          if str(type(fx)) == "<type 'dict'>":
                if fx.has_key('fieldLabel') and not fx.has_key('xtype'):
                  fx['xtype'] = 'textfield'
                if fx.has_key('title') and not fx.has_key('xtype'):
                  fx['xtype'] = 'label'
                  fx['text'] = fx['title']
		xobj = fx
		if xobj.has_key('xtype') == False or xobj['xtype'] in ['tbbutton', 'media', 'tabpanel', 'button']:
                  logging.info('skipping' + str(xobj))
                  continue
		if xobj.has_key('name') == False and xobj.has_key('id'):
                  xobj['name'] = xobj['id']
                if xobj.has_key('name') == False and xobj.has_key('id') == False:
                  xobj['name'] = xobj['title'].replace(' ', '')
                if xobj.has_key('fieldLabel'):
                  fl = xobj['fieldLabel']
                elif xobj.has_key('fieldlabel'):
                  fl = xobj['fieldlabel']
                else:
                  fl = xobj['name']
                #all django fields need to be told if the field is required
                if xobj.has_key('allowBlank') == False:
                  xobj['required'] = False
                else:
                  ab = xobj['allowBlank']
                  if str(ab) in ['False', 'false']:
                    xobj['required'] = True
                  else:
                    xobj['required'] = False
		if xobj['xtype'] == 'textfield':
			if dataobj.has_key(xobj['name']):
                                if xobj.has_key('vtype') and xobj['vtype'] == 'email':
                                  df[xobj['name']] = {'required': xobj['required'], 'xtype' :'EmailField', 'fieldLabel': fl, 'initial': dataobj[xobj['name']]}
                                  ff.append(df)
                                else:
                                  df[xobj['name']] = {'required': xobj['required'], 'xtype' :'CharField', 'fieldLabel': fl, 'initial': dataobj[xobj['name']]}
                                  ff.append(df)
			else:
                                if xobj.has_key('vtype') and xobj['vtype'] == 'email':
                                  df[xobj['name']] = {'required': xobj['required'], 'xtype' :'EmailField', 'fieldLabel': fl}
                                  ff.append(df)
                                else:
                                  df[xobj['name']] = {'required': xobj['required'], 'xtype' :'CharField', 'fieldLabel': fl}
                                  ff.append(df)

                # extjs form marks selected with "two". form submits : "entry.3.group":"two"
                # jsondata groupname:value 
		elif xobj['xtype'] == 'radio': 
			if (dataobj.has_key(xobj['name']) and xobj.has_key('inputValue')):
                          hdrdict = ff[0]['header']
                          afl = xobj['inputValue']
                          if xobj.has_key('fieldLabel'):
                            try:
                              afl = xobj['fieldLabel']
                            except:
                              afl = xobj['inputValue']
                          if hdrdict.has_key(xobj['name']):
                            choices = ff[0]['header'][xobj['name']]
                            newchoicelist = (  xobj['inputValue'], afl  )
                            ff[0]['header'][xobj['name']] = choices + ( newchoicelist,)
                          else:
                            #create the new radio group dict in header and add first choices
                            ff[0]['header'][xobj['name']] = ((  xobj['inputValue'], afl ),)
                            df[xobj['name']] = {'xtype' :'RadioField', 'name': xobj['name'],  'fieldLabel': fl, 'initial': dataobj[xobj['name']], 'inputValue':xobj['inputValue'] }
                            ff.append(df)
			else:
                          hdrdict = ff[0]['header']
                          afl = xobj['inputValue']
                          if xobj.has_key('fieldLabel'):
                            try:
                              afl = xobj['fieldLabel']
                            except:
                              afl = xobj['inputValue']
                          if hdrdict.has_key(xobj['name']):
                            choices = ff[0]['header'][xobj['name']]
                            newchoicelist = (  xobj['inputValue'], afl )
                            ff[0]['header'][xobj['name']] = choices + ( newchoicelist,)
                          else:
                            #create the new radio group dict in header and add first choices
                            ff[0]['header'][xobj['name']] = ((  xobj['inputValue'], afl),)
                            df[xobj['name']] = {'xtype' :'RadioField', 'name': xobj['name'],  'fieldLabel': fl,  'inputValue':xobj['inputValue'] }
                            ff.append(df)
		elif xobj['xtype'] == 'combo':
			if (dataobj.has_key(xobj['name']) and xobj.has_key('store')):
                                store = xobj['store']
                                newchoicelist = []
                                for s in store:
                                  newchoicetuple = (  s, s )
                                  newchoicelist.append(newchoicetuple)
                                df[xobj['name']] = {'xtype' :'ComboField', 'fieldLabel': xobj['fieldLabel'], 'store': tuple(newchoicelist), 'initial': dataobj[xobj['name']]}
                                ff.append(df)
			elif (not dataobj.has_key(xobj['name']) and xobj.has_key('store')):
                                store = xobj['store']
                                newchoicelist = []
                                for s in store:
                                  newchoicetuple = (  s, s )
                                  newchoicelist.append(newchoicetuple)
                                df[xobj['name']] = {'xtype' :'ComboField', 'fieldLabel': xobj['fieldLabel'], 'store': tuple(newchoicelist)}
                                ff.append(df)
			else:
                          df[xobj['name']] = {'xtype' :'ComboField', 'fieldLabel': xobj['fieldLabel']}
                          ff.append(df)
		elif xobj['xtype'] == 'checkbox':
                        if xobj.has_key('id'): xobj['name'] = xobj['id'] #assign groupname to checkbox name for google forms
			if dataobj.has_key(xobj['name']):
                          startv = dataobj[xobj['name']]
                          df[xobj['name']] = {'xtype' :'Checkbox', 'fieldLabel': xobj['fieldLabel'], 'initial': startv}
                          ff.append(df)
			else:
                                df[xobj['name']] = {'xtype' :'Checkbox', 'fieldLabel': xobj['fieldLabel']}
                                ff.append(df)
		elif xobj['xtype'] == 'datefield':
			if dataobj.has_key(xobj['name']):
                                df[xobj['name']] = {'xtype' :'DateField', 'fieldLabel': xobj['fieldLabel'], 'initial': dataobj[xobj['name']]}
                                ff.append(df)
			else:
                                df[xobj['name']] = {'xtype' :'DateField', 'fieldLabel': xobj['fieldLabel']}
                                ff.append(df)
		elif xobj['xtype'] in ['htmleditor', 'textarea']:
			if dataobj.has_key(xobj['name']):
                                df[xobj['name']] = {'required': xobj['required'], 'xtype' :'TextArea', 'fieldLabel': fl, 'initial': dataobj[xobj['name']]}
                                ff.append(df)
			else:
                                df[xobj['name']] = {'required': xobj['required'], 'xtype' :'TextArea', 'fieldLabel': fl, 'initial':''}
                                ff.append(df)
		elif xobj['xtype'] == 'label' and xobj.has_key('text'): #labels have text config, not fieldLabels
                        fl = xobj['text'] if xobj['text'] else fl
                        if xobj.has_key('name') == False:
                          titles = xobj['title']
                          title = titles.replace(' ','') #TODO find best way to strip all spaces from string
                          df[title] = {'xtype' :'Label', 'fieldLabel': fl, 'initial':''}
                        else:
                          df[xobj['name']] = {'xtype' :'Label', 'fieldLabel': fl, 'initial':''}
                        ff.append(df)
                else:
                  pass
        if htmlout:
          try:
            mf = DjFormFromXtype(ff)
          except:
            logging.info("problem init DjFormFromXtype probably unicode problem")
            raise
          try:
            res = mf.as_ul()
          except:
            logging.info("problem getting mf.as_ul probably unicode problem")
            raise
        else:
          res = ff
	return res



demoxtypeform = """
{"text": "1. Age", "forId": "entry_8", "xtype": "label", "id": "x-form-label-entry_8"},{"value": "", "fieldLabel": "1. Age", "xtype": "textfield", "name": "entry.8.single", "id": "entry_8"},{"text": "2. Gender", "forId": "entry_10", "xtype": "label", "id": "x-form-label-entry_10"},{"inputValue": "Male", "fieldLabel": "Male", "xtype": "radio", "name": "entry.10.group", "id": "group_10_1"},{"inputValue": "Female", "fieldLabel": "Female", "xtype": "radio", "name": "entry.10.group", "id": "group_10_2"},{"text": "3. Country of resident", "forId": "entry_12", "xtype": "label", "id": "x-form-label-entry_12"},{"value": "", "fieldLabel": "3. Country of resident", "xtype": "textfield", "name": "entry.12.single", "id": "entry_12"},{"text": "4. Visual impairment?", "forId": "entry_11", "xtype": "label", "id": "x-form-label-entry_11"},{"inputValue": "Color blind", "fieldLabel": "Color blind", "xtype": "radio", "name": "entry.11.group", "id": "group_11_1"},{"inputValue": "Other (i.e.) glasses", "fieldLabel": "Other (i.e.) glasses", "xtype": "radio", "name": "entry.11.group", "id": "group_11_2"},{"inputValue": "None", "fieldLabel": "None", "xtype": "radio", "name": "entry.11.group", "id": "group_11_3"},{"text": "5. How many hours do you play computer games?", "forId": "entry_14", "xtype": "label", "id": "x-form-label-entry_14"},{"fieldLabel": "5. How many hours do you play computer games?", "xtype": "combo", "store": ["0 hours per week", "1 hour per week", "2-4 hours per week", "5-7 hours per week", "8-10 hours per week", "more than 10 hours per week"], "id": "entry_14"},{"text": "6. How many hours do you surf the internet (i.e. check email, visit various websites)?", "forId": "entry_15", "xtype": "label", "id": "x-form-label-entry_15"},{"fieldLabel": "6. How many hours do you surf the internet (i.e. check email, visit various websites)?", "xtype": "combo", "store": ["0 hours per week", "1 hour per week", "2-4 hours per week", "5-7 hours per week", "8-10 hours per week", "more than 10 hours per week"], "id": "entry_15"},{"text": "1. What will happen, after pressing this button? I will", "forId": "entry_21", "xtype": "label", "id": "x-form-label-entry_21"},{"inputValue": "sign out of the program", "fieldLabel": "sign out of the program", "xtype": "radio", "name": "entry.21.group", "id": "group_21_1"},{"inputValue": "close the program", "fieldLabel": "close the program", "xtype": "radio", "name": "entry.21.group", "id": "group_21_2"},{"inputValue": "open a folder", "fieldLabel": "open a folder", "xtype": "radio", "name": "entry.21.group", "id": "group_21_3"},{"inputValue": "__option__", "fieldLabel": "option", "xtype": "radio", "name": "entry.21.group", "id": "other_option:21"},{"value": "", "fieldLabel": "option value", "xtype": "textfield", "name": "entry.21.group.other_option_", "id": "entry.21.group.other_option_"},{"text": "2. You want to access your personal information and view your training progression. Which button do you prefer?", "forId": "entry_22", "xtype": "label", "id": "x-form-label-entry_22"},{"inputValue": "Option 1", "fieldLabel": "Option 1", "xtype": "radio", "name": "entry.22.group", "id": "group_22_1"},{"inputValue": "Option 2", "fieldLabel": "Option 2", "xtype": "radio", "name": "entry.22.group", "id": "group_22_2"},{"inputValue": "Option 3", "fieldLabel": "Option 3", "xtype": "radio", "name": "entry.22.group", "id": "group_22_3"},{"inputValue": "Option 4", "fieldLabel": "Option 4", "xtype": "radio", "name": "entry.22.group", "id": "group_22_4"},{"inputValue": "Option 5", "fieldLabel": "Option 5", "xtype": "radio", "name": "entry.22.group", "id": "group_22_5"},{"inputValue": "Option 6", "fieldLabel": "Option 6", "xtype": "radio", "name": "entry.22.group", "id": "group_22_6"},{"inputValue": "Option 7", "fieldLabel": "Option 7", "xtype": "radio", "name": "entry.22.group", "id": "group_22_7"},{"text": "3. Which button do you prefer as a back button?", "forId": "entry_23", "xtype": "label", "id": "x-form-label-entry_23"},{"inputValue": "Option 1", "fieldLabel": "Option 1", "xtype": "radio", "name": "entry.23.group", "id": "group_23_1"},{"inputValue": "Option 2", "fieldLabel": "Option 2", "xtype": "radio", "name": "entry.23.group", "id": "group_23_2"},{"inputValue": "Option 3", "fieldLabel": "Option 3", "xtype": "radio", "name": "entry.23.group", "id": "group_23_3"},{"inputValue": "Option 4", "fieldLabel": "Option 4", "xtype": "radio", "name": "entry.23.group", "id": "group_23_4"},{"inputValue": "Option 5", "fieldLabel": "Option 5", "xtype": "radio", "name": "entry.23.group", "id": "group_23_5"},{"inputValue": "Option 6", "fieldLabel": "Option 6", "xtype": "radio", "name": "entry.23.group", "id": "group_23_6"},{"inputValue": "Option 7", "fieldLabel": "Option 7", "xtype": "radio", "name": "entry.23.group", "id": "group_23_7"},{"inputValue": "Option 8", "fieldLabel": "Option 8", "xtype": "radio", "name": "entry.23.group", "id": "group_23_8"},{"inputValue": "Option 9", "fieldLabel": "Option 9", "xtype": "radio", "name": "entry.23.group", "id": "group_23_9"},{"inputValue": "Option 10", "fieldLabel": "Option 10", "xtype": "radio", "name": "entry.23.group", "id": "group_23_10"},{"inputValue": "Option 11", "fieldLabel": "Option 11", "xtype": "radio", "name": "entry.23.group", "id": "group_23_11"},{"inputValue": "Option 12", "fieldLabel": "Option 12", "xtype": "radio", "name": "entry.23.group", "id": "group_23_12"},{"inputValue": "Option 13", "fieldLabel": "Option 13", "xtype": "radio", "name": "entry.23.group", "id": "group_23_13"},{"inputValue": "Option 14", "fieldLabel": "Option 14", "xtype": "radio", "name": "entry.23.group", "id": "group_23_14"},{"inputValue": "Option 15", "fieldLabel": "Option 15", "xtype": "radio", "name": "entry.23.group", "id": "group_23_15"},{"inputValue": "Option 16", "fieldLabel": "Option 16", "xtype": "radio", "name": "entry.23.group", "id": "group_23_16"},{"inputValue": "Option 17", "fieldLabel": "Option 17", "xtype": "radio", "name": "entry.23.group", "id": "group_23_17"},{"inputValue": "Option 18", "fieldLabel": "Option 18", "xtype": "radio", "name": "entry.23.group", "id": "group_23_18"},{"inputValue": "Option 19", "fieldLabel": "Option 19", "xtype": "radio", "name": "entry.23.group", "id": "group_23_19"},{"text": "1. Which button state do you prefer?", "forId": "entry_26", "xtype": "label", "id": "x-form-label-entry_26"},{"inputValue": "Option 1", "fieldLabel": "Option 1", "xtype": "radio", "name": "entry.26.group", "id": "group_26_1"},{"inputValue": "Option 2", "fieldLabel": "Option 2", "xtype": "radio", "name": "entry.26.group", "id": "group_26_2"},{"inputValue": "Option 3", "fieldLabel": "Option 3", "xtype": "radio", "name": "entry.26.group", "id": "group_26_3"},{"inputValue": "Option 4", "fieldLabel": "Option 4", "xtype": "radio", "name": "entry.26.group", "id": "group_26_4"},{"inputValue": "Option 5", "fieldLabel": "Option 5", "xtype": "radio", "name": "entry.26.group", "id": "group_26_5"},{"text": "2. Which button do you prefer as indicator for failing an exercise?", "forId": "entry_27", "xtype": "label", "id": "x-form-label-entry_27"},{"inputValue": "Option 1", "fieldLabel": "Option 1", "xtype": "radio", "name": "entry.27.group", "id": "group_27_1"},{"inputValue": "Option 2", "fieldLabel": "Option 2", "xtype": "radio", "name": "entry.27.group", "id": "group_27_2"},{"inputValue": "Option 3", "fieldLabel": "Option 3", "xtype": "radio", "name": "entry.27.group", "id": "group_27_3"},{"inputValue": "Option 4", "fieldLabel": "Option 4", "xtype": "radio", "name": "entry.27.group", "id": "group_27_4"},{"inputValue": "Option 5", "fieldLabel": "Option 5", "xtype": "radio", "name": "entry.27.group", "id": "group_27_5"},{"text": "3. Which button do you prefer as indicator for passing an exercise?", "forId": "entry_28", "xtype": "label", "id": "x-form-label-entry_28"},{"inputValue": "Option 1", "fieldLabel": "Option 1", "xtype": "radio", "name": "entry.28.group", "id": "group_28_1"},{"inputValue": "Option 2", "fieldLabel": "Option 2", "xtype": "radio", "name": "entry.28.group", "id": "group_28_2"},{"inputValue": "Option 3", "fieldLabel": "Option 3", "xtype": "radio", "name": "entry.28.group", "id": "group_28_3"},{"inputValue": "Option 4", "fieldLabel": "Option 4", "xtype": "radio", "name": "entry.28.group", "id": "group_28_4"},{"text": "1. Which layout color do you prefer?", "forId": "entry_31", "xtype": "label", "id": "x-form-label-entry_31"},{"inputValue": "Black\/Grey screen", "fieldLabel": "Black\/Grey screen", "xtype": "radio", "name": "entry.31.group", "id": "group_31_1"},{"inputValue": "White\/Green screen", "fieldLabel": "White\/Green screen", "xtype": "radio", "name": "entry.31.group", "id": "group_31_2"},{"inputValue": "Dark-Beige\/Blue screen", "fieldLabel": "Dark-Beige\/Blue screen", "xtype": "radio", "name": "entry.31.group", "id": "group_31_3"},{"text": "2. Which color do you associate with passing an exercise?", "forId": "entry_32", "xtype": "label", "id": "x-form-label-entry_32"},{"inputValue": "Red", "fieldLabel": "Red", "xtype": "radio", "name": "entry.32.group", "id": "group_32_1"},{"inputValue": "Green", "fieldLabel": "Green", "xtype": "radio", "name": "entry.32.group", "id": "group_32_2"},{"inputValue": "Blue", "fieldLabel": "Blue", "xtype": "radio", "name": "entry.32.group", "id": "group_32_3"},{"inputValue": "Yellow", "fieldLabel": "Yellow", "xtype": "radio", "name": "entry.32.group", "id": "group_32_4"},{"inputValue": "Magenta", "fieldLabel": "Magenta", "xtype": "radio", "name": "entry.32.group", "id": "group_32_5"},{"inputValue": "Cyan", "fieldLabel": "Cyan", "xtype": "radio", "name": "entry.32.group", "id": "group_32_6"},{"inputValue": "Black", "fieldLabel": "Black", "xtype": "radio", "name": "entry.32.group", "id": "group_32_7"},{"inputValue": "White", "fieldLabel": "White", "xtype": "radio", "name": "entry.32.group", "id": "group_32_8"},{"text": "3. Which color do you associate with failing an exercise?", "forId": "entry_39", "xtype": "label", "id": "x-form-label-entry_39"},{"inputValue": "Red", "fieldLabel": "Red", "xtype": "radio", "name": "entry.39.group", "id": "group_39_1"},{"inputValue": "Green", "fieldLabel": "Green", "xtype": "radio", "name": "entry.39.group", "id": "group_39_2"},{"inputValue": "Blue", "fieldLabel": "Blue", "xtype": "radio", "name": "entry.39.group", "id": "group_39_3"},{"inputValue": "Yellow", "fieldLabel": "Yellow", "xtype": "radio", "name": "entry.39.group", "id": "group_39_4"},{"inputValue": "Magenta", "fieldLabel": "Magenta", "xtype": "radio", "name": "entry.39.group", "id": "group_39_5"},{"inputValue": "Cyan", "fieldLabel": "Cyan", "xtype": "radio", "name": "entry.39.group", "id": "group_39_6"},{"inputValue": "Black", "fieldLabel": "Black", "xtype": "radio", "name": "entry.39.group", "id": "group_39_7"},{"inputValue": "White", "fieldLabel": "White", "xtype": "radio", "name": "entry.39.group", "id": "group_39_8"},{"text": "1. Which graph representation do you prefer for showing progression in skill?", "forId": "entry_37", "xtype": "label", "id": "x-form-label-entry_37"},{"inputValue": "Radar graph", "fieldLabel": "Radar graph", "xtype": "radio", "name": "entry.37.group", "id": "group_37_1"},{"inputValue": "Stacked graph (horizontal)", "fieldLabel": "Stacked graph (horizontal)", "xtype": "radio", "name": "entry.37.group", "id": "group_37_2"},{"inputValue": "Line graph", "fieldLabel": "Line graph", "xtype": "radio", "name": "entry.37.group", "id": "group_37_3"},{"inputValue": "Bar graph (vertical)", "fieldLabel": "Bar graph (vertical)", "xtype": "radio", "name": "entry.37.group", "id": "group_37_4"},{"inputValue": "Bar graph (horizontal)", "fieldLabel": "Bar graph (horizontal)", "xtype": "radio", "name": "entry.37.group", "id": "group_37_5"},{"inputValue": "Stacked graph (vertical)", "fieldLabel": "Stacked graph (vertical)", "xtype": "radio", "name": "entry.37.group", "id": "group_37_6"},{"text": "2. With which percentage have you passed a skill sufficiently?", "forId": "entry_38", "xtype": "label", "id": "x-form-label-entry_38"},{"inputValue": "0%", "fieldLabel": "0%", "xtype": "radio", "name": "entry.38.group", "id": "group_38_1"},{"inputValue": "50%", "fieldLabel": "50%", "xtype": "radio", "name": "entry.38.group", "id": "group_38_2"},{"inputValue": "80%", "fieldLabel": "80%", "xtype": "radio", "name": "entry.38.group", "id": "group_38_3"},{"inputValue": "100%", "fieldLabel": "100%", "xtype": "radio", "name": "entry.38.group", "id": "group_38_4"},{"text": "3. Which skill indicator do you prefer?", "forId": "entry_41", "xtype": "label", "id": "x-form-label-entry_41"},{"inputValue": "Grade (1 till 10)", "fieldLabel": "Grade (1 till 10)", "xtype": "radio", "name": "entry.41.group", "id": "group_41_1"},{"inputValue": "Percentage (0 till 100%)", "fieldLabel": "Percentage (0 till 100%)", "xtype": "radio", "name": "entry.41.group", "id": "group_41_2"},{"inputValue": "Level (A till F)", "fieldLabel": "Level (A till F)", "xtype": "radio", "name": "entry.41.group", "id": "group_41_3"},{"value": "0", "fieldLabel": "pageNumber", "xtype": "textfield", "name": "pageNumber", "id": "pageNumber"},{"value": "", "fieldLabel": "backupCache", "xtype": "textfield", "name": "backupCache", "id": "backupCache"}
"""

sampleformdata = """
{"entry.8.single":"24","entry.10.group":"Female","entry.12.single":"USA","entry.11.group":"None","entry_14":"2-4 hours per week","entry_15":"8-10 hours per week","entry.21.group":"open a folder","entry.21.group.other_option_":"","entry.22.group":"Option 7","pageNumber":"0","backupCache":""}
"""

if __name__ == '__main__':
    print '\n\n'
    print '<html>'
    print "Converted xtypes form to django form display as html"
    theoutput = xtypeToDjango(demoxtypeform, htmlout=True)
    print theoutput
    print "display html with json data values"
    theoutput = xtypeToDjango(demoxtypeform, sampleformdata, htmlout=True)
    print theoutput
    print '</html>'
